<?php

/*
 *  PagesTable
 *
 *  Copyright (c) 2011
 *
 *  This file is part of dolpheuscms.
 *  Version: $Id
 *  Created on 10-mrt-2011, 12:34:59
 *  Author: Harrie
 *
 *  This Content Management System is a product of http://www.twidel.nl.
 *
 *  No manipulation, reproduction or publication in any form without prior written
 *  permission from the copyright holder. Infrigements will result in legal action.
 */

class PagesTable extends Doctrine_Table
{

    public static function getInstance()
    {
        return Doctrine_Core::getTable('Pages');
    }

    /**
     * Used in: frontend
     * @return array with first page from pages table
     */
    public function getFirstPage()
    {
        // SELECT * FROM `pages` WHERE level = 1 ORDER BY lft ASC LIMIT 1
        $q = $this->createQuery()
                        ->where('level = 1')
                        ->orderBy('lft ASC')
                        ->limit('1');

        return $q->execute();
    }

    /**
     * Used in: frontend
     * @param string $pageName
     * @return array with info about $pagename
     */
    public function getPageName($url)
    {
        // SELECT * FROM `pages` WHERE url = $url
        $q = $this->createQuery()
                        ->where('url = ?', $url);

        return $q->execute();
    }

    /**
     * Used in: backend
     * @return array
     */
    public function getPageTemplates()
    {
        $template = array();
        //SELECT DISTINCT(template) AS templates FROM `pages`
        //$q = $this->createQuery()
        //                ->select('DISTINCT(template) AS template')
        //                ->from('Pages')
        //                ->orderBy('template');

        //$templates = $q->fetchArray();

        //foreach ($templates as $temp) {
        //    if ($temp != "") {
        //        $template[$temp['template']] = $temp['template'];
        //    }
        //}

        //return array_merge($template, $this->getTemplatesFromDir());
        return $this->getTemplatesFromDir();
    }

    /**
     * Get all the templates from the directory
     * @return array
     */
    private function getTemplatesFromDir()
    {
        return $this->listDirs('../apps/frontend/templates/');
    }

    /**
     * Loop through all files ending with .php
     * @param String $where
     * @return array
     */
    private function listDirs($where)
    {
        $template = array();
        $itemHandler = opendir($where);
        while (($item = readdir($itemHandler)) !== false) {
            if (preg_match("/.php/i", $item)) {
                $template[$item] = $item;
            }
        }
        return $template;
    }

}